//
//  PersonViewController.m
//  GoBangGraduationProject
//
//  Created by 刘人华 on 16/5/30.
//  Copyright © 2016年 dahua. All rights reserved.
//

#import "PersonViewController.h"
#import "DHPPChessBoardView.h"
#import "DHMCTool.h"
#import "HBPlaySoundUtil.h"
#import "SFDraggableDialogView.h"

@interface PersonViewController ()<DHPPChessDelegate,UIAlertViewDelegate,DHMCToolDelegate,SFDraggableDialogViewDelegate>{
    
    __weak IBOutlet UIImageView *bgImgView;
    __weak IBOutlet UIButton *soundBtn;
}

@property (nonatomic, strong) DHPPChessBoardView *chessView;
@property (nonatomic, strong) DHMCTool *mcTool;
@property (nonatomic, strong) DHUserModel *user;

@property (nonatomic, strong) UILabel *labName;
@property (nonatomic, strong) UILabel *labLevel;
@property (nonatomic, strong) UILabel *labCount;

@property (nonatomic, strong) UILabel *labEName;
@property (nonatomic, strong) UILabel *labELevel;
@property (nonatomic, strong) UILabel *labECount;

@end

@implementation PersonViewController

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:PPWhoWinNotify object:nil];
}

- (DHMCTool *)mcTool {
    
    if (!_mcTool) {
        _mcTool = [DHMCTool tool];
        _mcTool.delegate = self;
    }
    return _mcTool;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    if (self.isBlueTooth) {
        self.mcTool.delegate = self;
        [self.mcTool sendMessage:[ATLocal user].mj_JSONString error:nil];
        NSLog(@"发送:%@", [ATLocal user].mj_JSONString);
        if (!self.labEName.text) {
            [self.mcTool sendMessage:@"requestEInfo" error:nil];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    if (self.isBlueTooth) {
        [self.mcTool sendMessage:@"leave" error:nil];
        self.mcTool.delegate = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [bgImgView addSubview:({
        self.chessView = [[DHPPChessBoardView alloc] initWithFrame:CGRectMake(0, 50, SCREEN_W, SCREEN_W)];
        self.chessView.isBlueTooth = self.isBlueTooth;
        self.chessView.delegate = self;
        self.chessView.isAbleClick = YES;
        self.chessView;
    })];
    [self.view sendSubviewToBack:bgImgView];
    bgImgView.userInteractionEnabled = YES;
    soundBtn.selected = ![DHNSUserdefault getTheIsSounds];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whoWinWith:) name:PPWhoWinNotify object:nil];
    
    [self setUserView];
    [self reloadUserData];
}
- (void)setUserView {
    CGFloat labWidth = SCREEN_W / 2.0f;
    CGFloat labHeight = 30;
    [bgImgView addSubview:self.labName];
    [self.labName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgImgView.mas_top).offset(50 + SCREEN_W + 20);
        make.left.equalTo(bgImgView.mas_left);
        //make.center.equalTo(self.labName.superview);
        make.width.mas_equalTo(labWidth);
        make.height.mas_equalTo(labHeight);
    }];
    [bgImgView addSubview:self.labLevel];
    [self.labLevel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.labName.mas_bottom).offset(10);
        make.left.equalTo(self.labName.mas_left);
        make.width.mas_equalTo(labWidth);
        make.height.mas_equalTo(labHeight);
    }];
    [bgImgView addSubview:self.labCount];
    [self.labCount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.labLevel.mas_bottom).offset(10);
        make.left.equalTo(self.labName.mas_left);
        make.width.mas_equalTo(labWidth);
        make.height.mas_equalTo(labHeight);
    }];
    [bgImgView addSubview:self.labEName];
    [self.labEName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.labName);
        make.right.equalTo(bgImgView.mas_right);
        make.width.mas_equalTo(labWidth);
        make.height.mas_equalTo(labHeight);
    }];
    [bgImgView addSubview:self.labELevel];
    [self.labELevel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.labLevel);
        make.right.equalTo(self.labEName.mas_right);
        make.width.mas_equalTo(labWidth);
        make.height.mas_equalTo(labHeight);
    }];
    [bgImgView addSubview:self.labECount];
    [self.labECount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.labCount);
        make.right.equalTo(self.labEName.mas_right);
        make.width.mas_equalTo(labWidth);
        make.height.mas_equalTo(labHeight);
    }];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 18, 18)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 9;
    bgView.clipsToBounds = YES;
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(1, 1, 16, 16)];
    imgView.image = [UIImage imageNamed:ColorNames[[DHNSUserdefault getTheUserColor]]];
    [bgView addSubview:imgView];
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithCustomView:bgView];
    self.navigationItem.rightBarButtonItem = rightBtn;
}
- (void)reloadUserData {
    self.labName.text = self.user.userName;
    self.labLevel.text = [NSString stringWithFormat:@"%@ %ld%@", self.user.userLevelDesc, (long)self.user.grade, ATLocalizedString(@"Points", @"分")];
    self.labCount.text = [NSString stringWithFormat:@"%@:%@ %lu %@ %lu", ATLocalizedString(@"Record", @"战绩"), ATLocalizedString(@"Total", @"总"), (unsigned long)self.user.totalCount, ATLocalizedString(@"Win", @"胜"), (unsigned long)self.user.winCount];
    
}
- (IBAction)resetClick:(UIButton *)sender {
    self.view.userInteractionEnabled = YES;
    self.chessView.isAbleClick = YES;
    [self.chessView reset];
}
- (IBAction)undoClick:(UIButton *)sender {
    
    if (!self.isBlueTooth) {
        [self.chessView undo];
    } else {
        /**
         *  你下完了后
         */
        if (!self.chessView.isAbleClick) {
            [self.mcTool sendMessage:@"undo" error:nil];
        } else if (self.chessView.isAbleClick) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ATLocalizedString(@"Tips", @"温馨提示") message:ATLocalizedString(@"Tips_Content", @"你下棋了后才能马上点击悔棋") delegate:nil cancelButtonTitle:ATLocalizedString(@"Cancel", @"取消") otherButtonTitles: nil];
            [alert show];
        }
    }
}
- (IBAction)soundsClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    [DHNSUserdefault setupIsSounds:!sender.isSelected];
}
- (IBAction)quiklyClick:(UIButton *)sender {
    
    if (self.isBlueTooth) {
        [self.mcTool sendMessage:@"quikly" error:nil];
    } else {
        [[HBPlaySoundUtil shareForPlayingSoundEffectWith:@"quikly.wav"] play];
    }
}

#pragma mark - DHMCToolDelegate
- (void)session:(MCSession *)session didReceiveString:(NSString *)str fromPeer:(MCPeerID *)peer {
    
    NSLog(@"收到:%@",str);
    /**
     *  棋子
     */
    if (str.length == 10 && [[str substringToIndex:5] isEqualToString:@"color"]) {
        NSInteger x,y,index,aiIndex;
        x = [[str substringWithRange:NSMakeRange(5, 2)] integerValue];
        y = [[str substringWithRange:NSMakeRange(7, 2)] integerValue];
        index = [[str substringWithRange:NSMakeRange(9, 1)] integerValue];
        aiIndex = index == [DHNSUserdefault getTheUserColor] ? [DHNSUserdefault getTheAIColor] : index;
        self.labEName.textColor = App_Color_Light;
        self.labName.textColor = App_Color;
        [self.chessView addChessWithX:x y:y index:aiIndex type:OccupyTypeAI];
        self.chessView.isAbleClick = YES;
    }
    /*if (str.length == 9 && ([[str substringToIndex:5] isEqualToString:@"black"] || [[str substringToIndex:5] isEqualToString:@"white"])) {
        // 1.判断黑白棋
        BOOL isBlack;
        NSInteger x,y;
        isBlack = [[str substringToIndex:5] isEqualToString:@"black"] ? YES : NO;
        x = [[str substringWithRange:NSMakeRange(5, 2)] integerValue];
        y = [[str substringWithRange:NSMakeRange(7, 2)] integerValue];
        [self.chessView addChessWithX:x y:y isBlack:isBlack type:OccupyTypeAI];
        self.chessView.isAbleClick = YES;
    }*/
    if ([str isEqualToString:@"quikly"]) {
        [[HBPlaySoundUtil shareForPlayingSoundEffectWith:@"quikly.wav"] play];
    }
    if ([str isEqualToString:@"undo"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ATLocalizedString(@"Tips", @"温馨提示") message:ATLocalizedString(@"Enemy_want_rollback_isAgree", @"对方想悔棋，是否同意") delegate:self cancelButtonTitle:ATLocalizedString(@"No_way", @"没门") otherButtonTitles:ATLocalizedString(@"Agree", @"同意"), nil];
        [alert setTag:1];
        [alert show];
        self.chessView.isAbleClick = NO;
    }
    if ([str isEqualToString:@"sureUndo"]) {
        [self.chessView undo];
        self.chessView.isAbleClick = YES;
    }
    if ([str isEqualToString:@"dontUndo"]) {
        self.chessView.isAbleClick = NO;
    }
    if ([str isEqualToString:@"leave"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ATLocalizedString(@"Tips", @"温馨提示") message:ATLocalizedString(@"The_enemy_has_quit_this_game", @"对方已退出本局比赛") delegate:self cancelButtonTitle:ATLocalizedString(@"Cancel", @"取消") otherButtonTitles:ATLocalizedString(@"I_know", @"我知道了"), nil];
        [alert setTag:2];
        [alert show];
    }
    if ([str isEqualToString:@"requestEInfo"]) {
        [self.mcTool sendMessage:[ATLocal user].mj_JSONString error:nil];
    }
    if ([[DHUserModel mj_objectWithKeyValues:str] isKindOfClass:[DHUserModel class]]) {
        DHUserModel *enemyUser = [DHUserModel mj_objectWithKeyValues:str];
        self.labEName.text = enemyUser.userName;
        self.labELevel.text = [NSString stringWithFormat:@"%@ %ld%@", enemyUser.userLevelDesc, (long)enemyUser.grade, ATLocalizedString(@"Points", @"分")];
        self.labECount.text = [NSString stringWithFormat:@"%@:%@ %lu %@ %lu", ATLocalizedString(@"Record", @"战绩"), ATLocalizedString(@"Total", @"总"), (unsigned long)enemyUser.totalCount, ATLocalizedString(@"Win", @"胜"), (unsigned long)enemyUser.winCount];
    }
    
}
- (void)session:(MCSession *)session didChangeState:(MCSessionState)state fromPeer:(MCPeerID *)peer {
    
    
}

#pragma mark - DHPPChessDelegate
- (void)touchThePoint:(DHPoint *)point isWhite:(BOOL)isWhiteChess {
    if (self.isBlueTooth) {
        self.labName.textColor = App_Color_Light;
        self.labEName.textColor = App_Color;
        NSInteger index = [DHNSUserdefault getTheUserColor];
        NSMutableString *dataString = [NSMutableString stringWithFormat:@"color%02ld%02ld%ld", (long)point.x, point.y, (long)index];
        NSError *error;
        [self.mcTool sendMessage:dataString error:error];
        self.chessView.isAbleClick = NO;
        if (error) {
            NSLog(@"发送消息错误%@",[error localizedDescription]);
        }
    }
}

#pragma mark notify
- (void)whoWinWith:(NSNotification *)notify {
    
    OccupyType type = [notify.userInfo[@"type"] integerValue];
    switch (type) {
        case OccupyTypeUser:
        {
            SFDraggableDialogView *v = [SFDraggableDialogView drgViewWith:self titleText:ATLocalizedString(@"Game_Win_Of_You", @"You win!") photo:[UIImage imageNamed:@"winPic.jpg"] message:ATLocalizedString(@"Game_Win_Of_PP", @"You come, You see, You conquer!")];
            v.delegate = self;
            self.user.grade += 20;
            self.user.totalCount += 1;
            self.user.winCount += 1;
            [ATLocal updateUser:_user];
            [self reloadUserData];
            [self.mcTool sendMessage:[ATLocal user].mj_JSONString error:nil];
            [self.view addSubview:v];
        }
            break;
        case OccupyTypeAI:
        {
            SFDraggableDialogView *v = [SFDraggableDialogView drgViewWith:self titleText:ATLocalizedString(@"Game_Lose_Of_You", @"You lose!") photo:[UIImage imageNamed:@"lostPic.jpg"] message:ATLocalizedString(@"Where_fall_down_where_you_stand_up", @"Where fall down where you stand up")];
            v.delegate = self;
            self.user.grade -= 18;
            self.user.totalCount += 1;
            [ATLocal updateUser:_user];
            [self reloadUserData];
            [self.mcTool sendMessage:[ATLocal user].mj_JSONString error:nil];
            [self.view addSubview:v];

        }
            break;
        case OccupyTypeWhite:
        {
            SFDraggableDialogView *v = [SFDraggableDialogView drgViewWith:self titleText:ATLocalizedString(@"Game_Win_Of_White", @"White win!") photo:[UIImage imageNamed:@"winPic.jpg"] message:ATLocalizedString(@"Game_Win_Of_PP", @"You come, You see, You conquer!")];
            v.delegate = self;
            [self.view addSubview:v];
        }
            break;
        case OccupyTypeBlack:
        {
            SFDraggableDialogView *v = [SFDraggableDialogView drgViewWith:self titleText:ATLocalizedString(@"Game_Win_Of_Black", @"Black win!") photo:[UIImage imageNamed:@"winPic.jpg"] message:ATLocalizedString(@"Game_Win_Of_PP", @"You come, You see, You conquer!")];
            v.delegate = self;
            [self.view addSubview:v];
        }
            break;
            
        default:
            break;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (alertView.tag) {
        case 1:
            if (buttonIndex == 0) {
                [self.mcTool sendMessage:@"dontUndo" error:nil];
                self.chessView.isAbleClick = YES;
            } else {
                [self.chessView undo];
                [self.mcTool sendMessage:@"sureUndo" error:nil];
                self.chessView.isAbleClick = NO;
            }
            break;
        case 2:
            [self.navigationController popViewControllerAnimated:YES];
        default:
            break;
    }
}

- (void)draggableDialogView:(SFDraggableDialogView *)dialogView didPressFirstButton:(UIButton *)firstButton {
    
    self.view.userInteractionEnabled = YES;
    self.chessView.isAbleClick = YES;
    [self.chessView reset];
    [dialogView dismissWithDrop:YES];
}

- (void)draggableDialogView:(SFDraggableDialogView *)dialogView didPressSecondButton:(UIButton *)secondButton {
    if (self.isBlueTooth) {
        self.view.userInteractionEnabled = YES;
        self.chessView.isAbleClick = YES;
        [self.chessView reset];
        [dialogView dismissWithDrop:YES];
    }
}

#pragma mark - setter
- (DHUserModel *)user {
    if (!_user) {
        _user = [ATLocal user];
    }
    return _user;
}
- (UILabel *)newLab {
    UILabel *lab = [[UILabel alloc] init];
    lab.textColor = App_Color;
    lab.textAlignment = NSTextAlignmentCenter;
    return lab;
}
- (UILabel *)labName {
    if (!_labName) {
        _labName = [self newLab];
    }
    return _labName;
}
- (UILabel *)labLevel {
    if (!_labLevel) {
        _labLevel = [self newLab];
    }
    return _labLevel;
}
- (UILabel *)labCount {
    if (!_labCount) {
        _labCount = [self newLab];
    }
    return _labCount;
}
- (UILabel *)labEName {
    if (!_labEName) {
        _labEName = [self newLab];
    }
    return _labEName;
}
- (UILabel *)labELevel {
    if (!_labELevel) {
        _labELevel = [self newLab];
    }
    return _labELevel;
}
- (UILabel *)labECount {
    if (!_labECount) {
        _labECount = [self newLab];
    }
    return _labECount;
}

@end
